// drinkTea.js
Page({
  data: {
    teaLevel: 97, // 奶茶剩余量百分比
    isdrinking: false, // 是否正在喝
    isTouchingButton: false, // 按钮是否被按下
    statusMessage: '一杯没（标）热量的奶茶准备好了！', // 状态描述信息
    selectedToppings: [], // 改为数组，支持多选配料
    toppings: [
      { id: 'pearl', name: '珍珠', selected: false },
      { id: 'pudding', name: '布丁', selected: false },
      { id: 'grass-jelly', name: '仙草', selected: false },
      { id: 'oats', name: '燕麦粒', selected: false },
      { id: 'coconut', name: '椰果', selected: false },
      { id: 'red-bean', name: '红豆', selected: false },
      { id: 'taro-ball', name: '芋圆', selected: false }
    ],
    visibleToppings: [], // 可见的配料数组，包含所有类型
    maxToppingCounts: {
      pearl: 20,
      pudding: 8,
      'grass-jelly': 12,
      oats: 15,
      coconut: 10,
      'red-bean': 12,
      'taro-ball': 8
    },
    currentToppingCounts: {
      pearl: 0,
      pudding: 0,
      'grass-jelly': 0,
      oats: 0,
      coconut: 0,
      'red-bean': 0,
      'taro-ball': 0
    },
    // 声音模拟功能相关
    soundModeEnabled: false, // 是否开启声音模拟模式
    isRecording: false, // 是否正在录音
    hasRecordPermission: false, // 是否有录音权限
    soundTipVisible: false, // 是否显示声音提示
    recordManager: null, // 录音管理器
    soundDetectionTimer: null // 声音检测定时器
  },

  onLoad() {
    // 初始化摇一摇监听
    wx.startAccelerometer({
      interval: 'game' // 以游戏的更新频率监听加速度数据
    });
    // 监听加速度数据事件
    wx.onAccelerometerChange(this.onAccelerometerChange);
    
    // 初始化录音管理器
    this.initRecordManager();
  },

  onUnload() {
    // 页面卸载时停止监听
    wx.stopAccelerometer();
    wx.offAccelerometerChange(this.onAccelerometerChange);
    
    // 停止录音和相关定时器
    this.stopSoundDetection();
    if (this.data.recordManager) {
      this.data.recordManager.stop();
    }
    if (this.data.soundDetectionTimer) {
      clearTimeout(this.data.soundDetectionTimer);
    }
    if (this.soundStopTimer) {
      clearTimeout(this.soundStopTimer);
    }
    if (this.drinkingAnimation) {
      clearInterval(this.drinkingAnimation);
    }
  },

  // 初始化录音管理器
  initRecordManager() {
    const recordManager = wx.getRecorderManager();
    
    recordManager.onStart(() => {
      console.log('录音开始');
      this.setData({
        isRecording: true,
        statusMessage: '对着麦克风做吸气声音开始喝奶茶吧！'
      });
    });
    
    recordManager.onStop((res) => {
      console.log('录音结束', res);
      this.setData({
        isRecording: false
      });
    });
    
    recordManager.onError((err) => {
      console.error('录音错误', err);
      this.setData({
        isRecording: false,
        soundModeEnabled: false,
        statusMessage: '录音出现错误，已关闭声音模式'
      });
      wx.showToast({
        title: '录音出现错误',
        icon: 'none'
      });
    });
    
    // 监听录音音量变化
    recordManager.onFrameRecorded((res) => {
      // 通过音量大小判断是否在吸气
      const { frameBuffer } = res;
      this.analyzeAudioData(frameBuffer);
    });
    
    this.setData({
      recordManager: recordManager
    });
  },

  // 分析音频数据判断是否为吸气声
  analyzeAudioData(frameBuffer) {
    if (!this.data.soundModeEnabled || this.data.teaLevel <= 0) {
      return;
    }
    
    // 计算音量强度
    const audioData = new Int16Array(frameBuffer);
    let sum = 0;
    let maxAmplitude = 0;
    
    for (let i = 0; i < audioData.length; i++) {
      const amplitude = Math.abs(audioData[i]);
      sum += amplitude;
      maxAmplitude = Math.max(maxAmplitude, amplitude);
    }
    
    const averageVolume = sum / audioData.length;
    
    // 设置吸气声音的阈值 - 使用平均音量和峰值音量
    const INHALE_THRESHOLD_AVG = 800; // 平均音量阈值
    const INHALE_THRESHOLD_PEAK = 2000; // 峰值音量阈值
    
    // 检测持续的吸气声音（平均音量较高且有一定的峰值）
    const isInhaling = averageVolume > INHALE_THRESHOLD_AVG && maxAmplitude > INHALE_THRESHOLD_PEAK;
    
    if (isInhaling && !this.data.isdrinking) {
      // 检测到吸气声，开始喝奶茶
      this.startDrinkingBySound();
    } else if (!isInhaling && this.data.isdrinking) {
      // 声音停止，延迟一点停止喝奶茶（避免过于敏感）
      if (this.soundStopTimer) {
        clearTimeout(this.soundStopTimer);
      }
      this.soundStopTimer = setTimeout(() => {
        this.stopDrinking();
      }, 200); // 200ms延迟
    } else if (isInhaling && this.data.isdrinking) {
      // 继续吸气，清除停止定时器
      if (this.soundStopTimer) {
        clearTimeout(this.soundStopTimer);
        this.soundStopTimer = null;
      }
    }
  },

  // 通过声音开始喝奶茶
  startDrinkingBySound() {
    if (this.data.teaLevel <= 0 || this.data.isdrinking) return;
    
    this.setData({
      isdrinking: true,
      statusMessage: '检测到吸气声，正在喝奶茶...'
    });
    
    // 震动反馈
    wx.vibrateShort({
      type: 'light'
    });
    
    // 开始喝奶茶的动画
    this.drinkingAnimation = setInterval(() => {
      if (this.data.teaLevel <= 0) {
        this.stopDrinking();
        return;
      }
      
      const newLevel = Math.max(0, this.data.teaLevel - 0.8); // 声音模式喝得稍慢一些
      
      // 更新状态消息
      let message = '继续吸气来喝奶茶...';
      if (newLevel === 0) {
        message = '奶茶已经喝完了！';
      } else if (newLevel <= 10) {
        message = '最后一口，用力吸气！';
      } else if (newLevel <= 40) {
        message = '奶茶快喝完了，继续吸气~';
      } else if (newLevel <= 75) {
        message = '吸气声音很棒，继续！';
      }
      
      this.setData({
        teaLevel: newLevel,
        statusMessage: message
      });
      
      // 更新配料数量
      this.updateToppingsBasedOnTeaLevel(newLevel);
      
    }, 80); // 声音模式稍微慢一些
  },

  // 切换声音模拟模式
  toggleSoundMode(e) {
    const enabled = e.detail.value;
    
    if (enabled) {
      // 开启声音模式，需要先获取录音权限
      this.requestRecordPermission();
    } else {
      // 关闭声音模式
      this.stopSoundDetection();
      this.setData({
        soundModeEnabled: false,
        soundTipVisible: false,
        statusMessage: '声音模式已关闭'
      });
    }
  },

  // 请求录音权限
  requestRecordPermission() {
    wx.getSetting({
      success: (res) => {
        if (res.authSetting['scope.record']) {
          // 已有权限，直接开启声音模式
          this.enableSoundMode();
        } else {
          // 请求录音权限
          wx.authorize({
            scope: 'scope.record',
            success: () => {
              this.enableSoundMode();
            },
            fail: () => {
              // 权限被拒绝，引导用户手动开启
              wx.showModal({
                title: '需要录音权限',
                content: '声音模拟功能需要使用麦克风权限来检测吸气声音，请在设置中开启录音权限',
                confirmText: '去设置',
                success: (modalRes) => {
                  if (modalRes.confirm) {
                    wx.openSetting({
                      success: (settingRes) => {
                        if (settingRes.authSetting['scope.record']) {
                          this.enableSoundMode();
                        }
                      }
                    });
                  }
                }
              });
            }
          });
        }
      }
    });
  },

  // 开启声音模式
  enableSoundMode() {
    this.setData({
      soundModeEnabled: true,
      hasRecordPermission: true,
      soundTipVisible: true,
      statusMessage: '声音模式已开启！对着麦克风做吸气声音来喝奶茶吧！'
    });
    
    // 开始录音检测
    this.startSoundDetection();
    
    // 显示使用提示
    wx.showToast({
      title: '声音模式已开启',
      icon: 'success'
    });
    
    // 3秒后隐藏提示
    setTimeout(() => {
      this.setData({
        soundTipVisible: false
      });
    }, 3000);
  },

  // 开始声音检测
  startSoundDetection() {
    if (!this.data.recordManager) return;
    
    const options = {
      duration: 600000, // 10分钟最大录音时长
      sampleRate: 16000, // 采样率
      numberOfChannels: 1, // 声道数
      encodeBitRate: 96000, // 编码码率
      format: 'PCM', // 音频格式
      frameSize: 20 // 指定帧大小，单位 KB
    };
    
    this.data.recordManager.start(options);
  },

  // 停止声音检测
  stopSoundDetection() {
    if (this.data.recordManager && this.data.isRecording) {
      this.data.recordManager.stop();
    }
    
    if (this.data.isdrinking) {
      this.stopDrinking();
    }
    
    this.setData({
      isRecording: false
    });
  },

  // 生成指定类型的配料
  generateToppings(type, count) {
    const toppings = [];
    
    for (let i = 0; i < count; i++) {
      toppings.push({
        type: type,
        left: Math.random() * 70 + 15, // 15% - 85% 范围内的随机水平位置，减小移动幅度
        top: Math.random() * 70 + 15,  // 15% - 85% 范围内的随机垂直位置，减小移动幅度
        id: `${type}_${i}`
      });
    }
    
    return toppings;
  },

  // 更新所有配料的显示
  updateAllToppings() {
    let allToppings = [];
    const selectedToppings = this.data.selectedToppings;
    const maxCounts = this.data.maxToppingCounts;
    
    selectedToppings.forEach(toppingType => {
      const count = maxCounts[toppingType];
      const toppings = this.generateToppings(toppingType, count);
      allToppings = allToppings.concat(toppings);
    });
    
    // 更新当前配料数量
    const currentCounts = {};
    selectedToppings.forEach(type => {
      currentCounts[type] = maxCounts[type];
    });
    
    this.setData({
      visibleToppings: allToppings,
      currentToppingCounts: currentCounts
    });
  },

  // 根据奶茶量更新配料数量
  updateToppingsBasedOnTeaLevel(teaLevel) {
    const ratio = teaLevel / 97; // 根据初始茶量计算比例
    let allToppings = [];
    const selectedToppings = this.data.selectedToppings;
    const maxCounts = this.data.maxToppingCounts;
    const newCurrentCounts = {};
    
    selectedToppings.forEach(toppingType => {
      const maxCount = maxCounts[toppingType];
      const newCount = Math.max(0, Math.floor(maxCount * ratio));
      newCurrentCounts[toppingType] = newCount;
      
      const toppings = this.generateToppings(toppingType, newCount);
      allToppings = allToppings.concat(toppings);
    });
    
    this.setData({
      visibleToppings: allToppings,
      currentToppingCounts: newCurrentCounts
    });
  },

  // 切换配料选择状态
  toggleTopping(e) {
    const toppingId = e.currentTarget.dataset.topping;
    const toppings = this.data.toppings.map(topping => {
      if (topping.id === toppingId) {
        return { ...topping, selected: !topping.selected };
      }
      return topping;
    });
    
    // 更新选中的配料列表
    const selectedToppings = toppings
      .filter(topping => topping.selected)
      .map(topping => topping.id);
    
    this.setData({
      toppings: toppings,
      selectedToppings: selectedToppings
    });
    
    // 重新生成配料显示
    this.updateAllToppings();
  },

  // 摇一摇监听函数
  onAccelerometerChange(res) {
    // 如果开启了声音模式，禁用摇一摇功能
    if (this.data.soundModeEnabled) {
      return;
    }
    
    // 设置摇动阈值，当加速度变化超过阈值时认为是在摇动
    const SHAKE_THRESHOLD = 2.5;
    const { x, y, z } = res;
    const acceleration = Math.sqrt(x * x + y * y + z * z);
    
    if (acceleration > SHAKE_THRESHOLD && !this.data.isdrinking && this.data.teaLevel > 0) {
      // 开始喝奶茶
      this.startDrinking();
      
      // 震动反馈
      wx.vibrateShort({
        type: 'medium'
      });
      
      // 1秒后自动停止
      setTimeout(() => {
        this.stopDrinking();
      }, 1000);
    }
  },

  // 按下按钮开始喝奶茶
  startDrinking() {
    if (this.data.teaLevel <= 0) return;
    
    this.setData({
      isdrinking: true,
      isTouchingButton: true,
      statusMessage: '正在喝奶茶...'
    });
    
    // 开始喝奶茶的动画
    this.drinkingAnimation = setInterval(() => {
      if (this.data.teaLevel <= 0) {
        this.stopDrinking();
        return;
      }
      
      const newLevel = Math.max(0, this.data.teaLevel - 1);
      // 更新状态消息
      let message = '正在喝奶茶...';
      
      if (newLevel === 0) {
        message = '奶茶已经喝完了！';
      } else if (newLevel <= 10) {
        message = '最后一口，好好享受吧！';
      } else if (newLevel <= 40) {
        message = '奶茶快喝完了，慢慢品尝~';
      } else if (newLevel <= 75) {
        message = '奶茶喝了一半，滋味如何？';
      }
      
      this.setData({
        teaLevel: newLevel,
        statusMessage: message
      });
      
      // 更新配料数量
      this.updateToppingsBasedOnTeaLevel(newLevel);
      
    }, 50); // 每50毫秒减少1%的奶茶量
  },
  
  // 松开按钮停止喝奶茶
  stopDrinking() {
    clearInterval(this.drinkingAnimation);
    
    // 根据当前茶量更新状态消息
    let message = this.data.statusMessage;
    const level = this.data.teaLevel;
    
    if (level === 0) {
      message = '奶茶已经喝完了！';
    } else if (level <= 10) {
      message = '只剩最后一点点了，珍惜吧~';
    } else if (level <= 40) {
      message = '奶茶还剩不到一半了';
    } else if (level <= 75) {
      message = '奶茶还有半杯，慢慢品尝';
    }
    
    this.setData({
      isdrinking: false,
      isTouchingButton: false,
      statusMessage: message
    });
  },
  
  // 重置奶茶量
  resetTea() {
    this.setData({
      teaLevel: 97,
      statusMessage: '一杯没（标）热量的奶茶准备好了！'
    });
    
    // 重新生成配料
    this.updateAllToppings();
  },
  
  // 按钮触摸开始
  buttonTouchStart() {
    this.startDrinking();
  },
  
  // 按钮触摸结束
  buttonTouchEnd() {
    this.stopDrinking();
  },

  // 分享给好友 (原生分享按钮会触发此函数)
  onShareAppMessage() {
    const toppingText = this.getToppingText();
    const levelText = this.getTeaLevelText();
    
    return {
      title: `我正在喝${toppingText}奶茶，${levelText}，来一起喝奶茶吧！`,
      path: '/pages/drinkTea/drinkTea',
      // 不指定图片，使用小程序默认图标
    };
  },

  // 分享到朋友圈 (原生分享按钮会触发此函数)
  onShareTimeline() {
    const toppingText = this.getToppingText();
    const levelText = this.getTeaLevelText();
    
    return {
      title: `我的${toppingText}奶茶${levelText}，一起来体验吧！`,
      query: 'from=timeline',
      // 不指定图片，使用小程序默认图标
    };
  },

  // 获取当前配料文本描述
  getToppingText() {
    const selectedToppings = this.data.selectedToppings;
    if (selectedToppings.length === 0) {
      return '无配料';
    }
    
    const toppingNames = selectedToppings.map(id => {
      const topping = this.data.toppings.find(t => t.id === id);
      return topping ? topping.name : '';
    }).filter(name => name);
    
    return toppingNames.join('+');
  },

  // 获取奶茶剩余量描述
  getTeaLevelText() {
    const level = this.data.teaLevel;
    
    if (level <= 0) {
      return '已经喝完了';
    } else if (level <= 10) {
      return '只剩最后一口了';
    } else if (level <= 40) {
      return '已经喝了大半杯了';
    } else if (level <= 75) {
      return '已经喝了半杯了';
    } else {
      return '刚开始喝';
    }
  }
}); 